<?php

/**
 * 采购需求列表
 * QiuXiangCheng
 * Date 2016/08/19
 */
class Backup_DemandController extends Controller_NeedLogin {

	/**
	 * 特采申请MODEL
	 * @var Object
	 */
	private $purchaseModel;

	/**
	 * 特采需求MODEL
	 * @var Object
	 */
	private $specialDemand;

	private $departmentModel;

	/**
	 * 即将导入的excel的相对路径
	 * @var String
	 */
	private $excelPath;

	/**
	 * 异常报告
	 * @var String
	 */
	private $exception = '';

	private static $exceptions = '';
	private $_backup_Model_Story;
	/**
	 * 初始化
	 */
	public function init() {

		parent::init();
		$this->departmentModel = new Base_Model_Department;
		$this->purchaseModel = new Purchase_Model_ProductCheck;
		$this->specialDemand = new Purchase_Model_SpecialDemand;
		$this->storyModel = new Application_Model_Story;
	}

	/**
	 * 采购需求
	 * @return null
	 */
	public function indexAction() {
		$data = [];
		$limit = $this->_PAGELIMITER($data, $this->page_size);
		$depts = $this->departmentModel->getDepartment();
		$this->smarty->assign('depts', $this->departmentModel->gertDepartmentHTML($depts));
		$where = Backup_Model_Demand::purchaseWhere($data);
		$purchase = Backup_Model_Demand::purchaseUnoin($where, $limit['limit']);
		foreach ($purchase as &$_story) {
			$_storyQuantityModifyLog = $this->_storyQuantityModifyLog($_story['id']);
			$_story['c_story_quantity_modify_log'] = $_storyQuantityModifyLog['c'] ?? "";
			$_story['a_story_quantity_modify_log'] = $_storyQuantityModifyLog['a'] ?? "";
			$_story['b_story_quantity_modify_log'] = $_storyQuantityModifyLog['b'] ?? "";

			$_story['storyExamineLog'] = $this->_storyExamineLog($_story['id']);
		}
		$pageAmount = Backup_Model_Demand::fetchCountDemands($where);

		$defaultTableFiled = 'goods_sn,thumb_url,product_name,purchase_price,stock_can_allot,sale_count,actual_count,sale_warning,a_story_quantity,b_story_quantity,c_story_quantity,story_quantity_total,purchaser,life_cycle';
		$productTableFiled = isset($_COOKIE['productTableFiled']) && !empty($_COOKIE['productTableFiled']) ? $_COOKIE['productTableFiled'] : $defaultTableFiled;
		$productTableFiled = array_filter(explode(',', $productTableFiled));
		$this->smarty->assign('productTableFiled', $productTableFiled);

		$queryParameter = $this->getRequest()->getQuery();
		//获取分类的父级信息，用于设置查询页面类别筛选条件选择框
		$queryParameter['catalogPath'] = '';
		if (isset($queryParameter['catalog_id']) && $queryParameter['catalog_id']) {
			$ProductCatalogModel = new Application_Model_ProductCatalog();
			$catalogPath = $ProductCatalogModel->getDetailById($queryParameter['catalog_id'], ['path']);
			$queryParameter['catalogPath'] = $catalogPath['path'] ?? "";
			$queryParameter['catalogPath'] = ltrim($queryParameter['catalogPath'], "0,");
		}

		$this->smarty->assign('p', $purchase);
		$this->smarty->assign('data', json_encode($this->getRequest()->getParams()));
		$this->smarty->assign('warehouse', Base_Model_Warehouse::fetchWarehouseNameByCode());
		$this->smarty->assign('sale_day', Backup_Model_Demand::SALE_DATA);
		$this->smarty->assign('pstatus', Backup_Model_Demand::PRODUCT_STATUS);
		$this->smarty->assign('transferStatus', Backup_Model_Demand::TRANSFER_STATUS);
		$this->smarty->assign('examine', Backup_Model_Demand::EXAMINE_STATUS);
		$this->smarty->assign('stockType', Backup_Model_Demand::$stocking_type);
		$this->smarty->assign('queryParameter', $queryParameter);
		$this->smarty->assign('page', @$this->page($pageAmount, $data['action']));
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('demand_index.php');
	}

	/**
	 * 采购需求拦截列表
	 */
	public function storyInterceptAction() {
		$this->db = Model_Db::getInstance();
		$queryParameter = $this->getRequest()->getQuery();

		$tableSql = 'SELECT %fields% FROM b_intercept_story left JOIN p_product  ON b_intercept_story.goods_sn = p_product.goods_sn';
		$where = "";

		//sku查询
		if ($queryParameter['goods_sn'] ?? "") {
			$goodsSn = explode(',', $queryParameter['goods_sn']);
			$where .= "AND " . $this->db->quoteInto("b_intercept_story.goods_sn in(?)", $goodsSn) . " ";
		}
		//仓库查询
		if ($queryParameter['warehouse'] ?? "") {
			$where .= "AND " . $this->db->quoteInto("b_intercept_story.story_warehouse =?", $queryParameter['warehouse']) . " ";
		}

		$querySql = $tableSql;
		if ($where) {
			$querySql .= " where " . ltrim($where, 'AND');
		}

		$countQuerySql = str_replace("%fields%", "count(*)", $querySql);
		$allAmount = $this->db->fetchOne($countQuerySql);
		$pageLink = "";
		$interceptStoryList = [];
		if ($allAmount) {
			$queryField = 'b_intercept_story.*, p_product.thumb_url,p_product.original_img_url, p_product.product_name';
			$querySql = str_replace("%fields%", $queryField, $querySql);
			$page = (int) ($this->getRequest()->getParam('page') ?? 1);
			$pageLength = (int) $this->page_size;

			$limitSql = " limit " . ($page - 1) * $pageLength . "," . $pageLength;
			$querySql .= $limitSql;
			$interceptStoryList = $this->db->fetchAll($querySql);
			$pageLink = $this->page($allAmount, $pageLength);

			//获取产品的需求仓库名称和销售仓库名称
			$productStoryWarehouseList = array_unique(array_column($interceptStoryList, 'story_warehouse'));
			$productSalesWarehouseList = array_unique(array_column($interceptStoryList, 'sales_warehouse'));
			$warehouseList = array_merge($productStoryWarehouseList, $productSalesWarehouseList);
			$warehouseList = array_unique($warehouseList);
			$warehouseModel = new Application_Model_Warehouse();
			$warehouseNameList = $warehouseModel->getWarehouseByCode($warehouseList, ['warehouse_name', 'warehouse_code']);
			$warehouseNameList = array_column($warehouseNameList, 'warehouse_name', 'warehouse_code');
			foreach ($interceptStoryList as &$interceptStory) {
				$interceptStory['storyWarehouseName'] = $warehouseNameList[$interceptStory['story_warehouse']] ?? "";
				$interceptStory['salesWarehouseName'] = $warehouseNameList[$interceptStory['sales_warehouse']] ?? "";
			}
			unset($interceptStory);
		}

		$this->smarty->assign('list', $interceptStoryList);
		$this->smarty->assign('pageLink', $pageLink);
		$this->smarty->assign('queryParameter', $queryParameter);
		$this->smarty->assign('ression', Backup_Model_Demand::STORY_INTERCEPT_RESSION);
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('demand_intercept_log.php');
	}

	/**
	 * 需求审核
	 * @return [type] [description]
	 */
	public function checkAction() {
		$queryParameter = $this->getRequest()->getParams();
		$storyId = $queryParameter['story_id'];
		$storyId = explode(',', $storyId);
		$operationType = $queryParameter['operation_type'];
		switch ($operationType) {
			case 1:
			case 5:
				if (!in_array(441, $this->_session->currentLoginUser['auth'])) {
					$this->_helper->json(['success'=>false,'msg'=>'您没有小组长审核/驳回的权限']);
				};
				break;
			case 2:
			case 6:
				if (!in_array(442, $this->_session->currentLoginUser['auth'])) {
					$this->_helper->json(['success'=>false,'msg'=>'您没有大组长审核/驳回的权限']);
				};
				break;
			case 3:
			case 7:
				if (!in_array(443, $this->_session->currentLoginUser['auth'])) {
					$this->_helper->json(['success'=>false,'msg'=>'您没有主管审核/驳回的权限']);
				};
				break;
			case 4:
			case 8:
				if (!in_array(444, $this->_session->currentLoginUser['auth'])) {
					$this->_helper->json(['success'=>false,'msg'=>'您没有经理审核/驳回的权限']);
				};
				break;
		}
		//操作权限判断
		$storyModel = new Backup_Model_Story();
		foreach ($storyId as $_storyId) {
			$checkResult = $storyModel->check($_storyId, $operationType);
			if ($checkResult === false) {
				$this->_helper->json(['success' => false, 'msg' => '需求:' . $_storyId . '审核失败，原因是:' . $storyModel->getErrorMsg()]);
				exit;
			}
		}
		$this->_helper->json(['success' => true, 'msg' => '审核成功！']);
	}

	/**
	 * 被驳回需求列表
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function rejectListAction($value = '') {
		$this->db = Model_Db::getInstance();
		$queryParameter = $this->getRequest()->getQuery();

		$tableSql = "select %fields% from b_reject_story as reject_story
		        left join b_story as story on reject_story.story_id=story.id
		        left join p_product as product on story.goods_sn=product.goods_sn
		        left join p_product_warehouse_stock as stock on stock.goods_sn=story.goods_sn and stock.warehouse_code=story.warehouse_code
		        ";
		$where = '';
		//产品类别查询
		if ($queryParameter['product_category'] ?? "") {
			$productCatalogModel = new Application_Model_ProductCatalog();
			$allChildCatalogId = $productCatalogModel->getAllChildCatalog($queryParameter['product_category'], ['id']);
			$allChildCatalogId = array_column($allChildCatalogId, 'id');
			$where .= "AND " . $this->db->quoteInto("product.catalog_id in(?)", $allChildCatalogId) . " ";
		}

		//搜索关键字
		if ($queryParameter['search_keyword_type'] ?? "") {
			if ($queryParameter['search_keyword'] ?? "") {
				if ($queryParameter['search_keyword_type'] == 'goods_sn') {
					$where .= $this->db->quoteInto('AND story.goods_sn in (?) ', explode(',', $queryParameter['search_keyword']));
				} else {
					$where .= $this->db->quoteInto('AND product.product_name = ? ', $queryParameter['search_keyword']);
				}
			}
		}

		//仓库查询
		if ($queryParameter['warehouse'] ?? "") {
			$where .= "AND " . $this->db->quoteInto("story.warehouse_code =?", $queryParameter['warehouse']) . " ";
		}
		$querySql = $tableSql;
		if ($where) {
			$querySql .= " where " . ltrim($where, 'AND');
		}

		$countQuerySql = str_replace("%fields%", "count(*)", $querySql);
		$allAmount = $this->db->fetchOne($countQuerySql);

		$rejectStoryList = [];
		$pageLink = "";
		if ($allAmount) {
			$queryField = "product.goods_sn,product.thumb_url,product.original_img_url,product.product_name,product.product_status,
						   stock.last_storage_time,stock.stock_order_nums,.stock.base_stock,stock.out_cycle,
						   story.id as story_id ,story.*,
						   reject_story.*";
			$querySql = str_replace("%fields%", $queryField, $querySql);
			$page = (int) ($this->getRequest()->getParam('page') ?? 1);
			$pageLength = (int) $this->page_size;

			$limitSql = " limit " . ($page - 1) * $pageLength . "," . $pageLength;
			$querySql .= $limitSql;
			$rejectStoryList = $this->db->fetchAll($querySql);
			$pageLink = $this->page($allAmount, $pageLength);
		}

		if (!empty($rejectStoryList)) {
			$productSalesCommonModel = new Application_Model_ProductSales();
			//获取采购信息
			$_goodsSnArr = array_column($rejectStoryList, 'goods_sn');
			$productPurchase = $this->db->fetchAssoc('select goods_sn,purchaser,purchase_price from p_product_purchase where ' . $this->db->quoteInto("goods_sn in(?)", $_goodsSnArr));
			$productPurchaseInfo = $this->db->fetchAssoc('select goods_sn,min_order from p_product_purchase_info where ' . $this->db->quoteInto("goods_sn in(?)", $_goodsSnArr));

			foreach ($rejectStoryList as &$_oneRejectStory) {
				//获取查询结果商品的销量信息
				$productSalesInfo = $productSalesCommonModel->getOne($_oneRejectStory['goods_sn'], $_oneRejectStory['warehouse_code']);
				$productSalesInfo = (array) $productSalesInfo;
				//真实销量
				
				$_oneRejectStory['the7DayActualSales'] = $productActualSalesInfo['real_sale_7'] ?? 0;
				$_oneRejectStory['the15DayActualSales'] = $productActualSalesInfo['real_sale_15'] ?? 0;
				$_oneRejectStory['the30DayActualSales'] = $productActualSalesInfo['real_sale_30'] ?? 0;
				//备货销量
				
				$_oneRejectStory['the7DayBackupSales'] = $productBackupSalesInfo['sale_7'] ?? 0;
				$_oneRejectStory['the15DayBackupSales'] = $productBackupSalesInfo['sale_15'] ?? 0;
				$_oneRejectStory['the30DayBackupSales'] = $productBackupSalesInfo['sale_30'] ?? 0;

				//采购信息
				$_oneRejectStory['purchaser'] = $productPurchase[$_oneRejectStory['goods_sn']]['purchaser'] ?? "";
				$_oneRejectStory['purchase_price'] = $productPurchase[$_oneRejectStory['goods_sn']]['purchase_price'] ?? "";
				$_oneRejectStory['min_order'] = $productPurchaseInfo[$_oneRejectStory['goods_sn']]['min_order'] ?? "";

				$_storyQuantityModifyLog = $this->_storyQuantityModifyLog($_oneRejectStory['story_id']);
				$_oneRejectStory['c_story_quantity_modify_log'] = $_storyQuantityModifyLog['c'] ?? "";
				$_oneRejectStory['a_story_quantity_modify_log'] = $_storyQuantityModifyLog['a'] ?? "";
				$_oneRejectStory['b_story_quantity_modify_log'] = $_storyQuantityModifyLog['b'] ?? "";

			}

		}

		//获取分类的父级信息，用于设置查询页面类别筛选条件选择框
		$queryParameter['catalogPath'] = '';
		if (isset($queryParameter['product_category']) && $queryParameter['product_category']) {
			$ProductCatalogModel = new Application_Model_ProductCatalog();
			$catalogPath = $ProductCatalogModel->getDetailById($queryParameter['product_category'], ['path']);
			$queryParameter['catalogPath'] = $catalogPath['path'] ?? "";
			$queryParameter['catalogPath'] = ltrim($queryParameter['catalogPath'], "0,");
		}

		$departmentModel = new Application_Model_Department();
		$hasWarehouseDep = $departmentModel->hasWarehouse();
		$this->smarty->assign('hasWarehouseDep', $hasWarehouseDep);
		$this->smarty->assign('productStatus', [1 => '正常', '断货', '停产']);
		$this->smarty->assign('rejectStoryList', $rejectStoryList);
		$this->smarty->assign('pageLink', $pageLink);
		$this->smarty->assign('queryParameter', $queryParameter);

		$defaultTableFiled = 'goods_sn,thumb_url,product_name,purchase_price,actualsales,backupsales,a_story_quantity,b_story_quantity,c_story_quantity,abc_story_amount,purchaser,numbers,platform_warehouse,warehouse_code,last_storage_time,reject_handler,reject_datetime,reject_reason_type,reject_reason_detail,handler,reject_result,operate';
		$productTableFiled = isset($_COOKIE['table_field_reject_story']) && !empty($_COOKIE['table_field_reject_story']) ? $_COOKIE['table_field_reject_story'] : $defaultTableFiled;
		$productTableFiled = array_filter(explode(',', $productTableFiled));
		$this->smarty->assign('productTableFiled', $productTableFiled);
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('rejectStoryList.tpl');
	}

	/**
	 * 采购被驳回的需求
	 * @return [type] [description]
	 */
	public function purchaseAction() {
		$queryParameter = $this->getRequest()->getQuery();
		$storyId = $queryParameter['story_id'];

		$storyIdArr = explode(',', $storyId);
		$rejectStoryModel = new Backup_Model_RejectStory();

		foreach ($storyIdArr as $_storyId) {
			$result = $rejectStoryModel->purchase($_storyId);
			if ($result === false) {
				$this->_helper->json(['success' => false, 'msg' => '采购操作失败,原因是：' . $rejectStoryModel->getErrorMsg()]);
				exit;
			}
		}

		$this->_helper->json(['success' => true, 'msg' => '采购操作成功！']);
	}

	/**
	 * 取消 “驳回需求” 的采购
	 * @return [type] [description]
	 */
	public function cancleAction() {
		$queryParameter = $this->getRequest()->getQuery();
		$storyId = $queryParameter['story_id'];

		$storyIdArr = explode(',', $storyId);
		$rejectStoryModel = new Backup_Model_RejectStory();

		foreach ($storyIdArr as $_storyId) {
			$result = $rejectStoryModel->cancle($_storyId);
			if ($result === false) {
				$this->_helper->json(['success' => false, 'msg' => '取消失败,原因是：' . $rejectStoryModel->getErrorMsg()]);
				exit;
			}
		}

		$this->_helper->json(['success' => true, 'msg' => '取消成功！']);
	}

	/**
	 * 修改被驳回需求的数量
	 * @return [type] [description]
	 */
	public function modifyQuantityAction() {
		$queryParameter = $this->getRequest()->getQuery();
		$storyId = (int) $queryParameter['story_id'];
		$storyType = $queryParameter['story_type'];
		$modifyedQuantity = $queryParameter['quantity'];
		$modifyedQuantity = (int) $modifyedQuantity;

		if (!in_array($storyType, ['b', 'c'])) {
			$this->_helper->json(['success' => false, 'msg' => '只能修改b,c需求的数量！']);
		}

		if ($modifyedQuantity < 0) {
			$this->_helper->json(['success' => false, 'msg' => '修改后的备货数量不能小于零！']);
		}

		$storyModel = new Application_Model_Story();
		$storyInfo = $storyModel->getOneById($storyId);
		if (!$storyInfo) {
			$this->_helper->json(['success' => false, 'msg' => '未找到需求！']);
		}

		$storyTypeQuantityFields = ['a' => 'a_story_quantity', 'b' => 'b_story_quantity', 'c' => 'c_story_quantity'];
		if ($modifyedQuantity > (1.3) * $storyInfo[$storyTypeQuantityFields[$storyType]]) {
			$this->_helper->json(['success' => false, 'msg' => '修改后的备货数量不能大于需求原数量的30%！']);
		}

		$modifyUser = $this->currentLoginUser('user_name');
		$updateReason = '人为修改';
		$updateQuantityResult = $storyModel->updateQuantity($storyId, $storyType, $modifyedQuantity, $updateReason, $modifyUser);

		if ($updateQuantityResult === false) {
			$this->_helper->json(['success' => false, 'msg' => $storyModel->getErrorMsg()]);
		}

		$this->_helper->json(['success' => true, 'msg' => '修改成功！']);
	}

	/**
	 * 获取需求数量变更日志
	 * @param  int    $storyId   [description]
	 * @param  string $separator [description]
	 * @return [type]            [description]
	 */
	protected function _storyQuantityModifyLog(int $storyId, $separator = '<br/>') {
		$allStoryModifyLog = $this->storyModel->getStoryQuantityModifyLog($storyId);
		if (!$allStoryModifyLog) {
			return '';
		}
		$log = [];
		foreach ($allStoryModifyLog as $_modifyLog) {
			$log[$_modifyLog['story_type']] = ($log[$_modifyLog['story_type']] ?? "") . $_modifyLog['remark'] . $separator;
		}
		return $log;
	}

	protected function _storyExamineLog($storyId) {
		$this->_backup_Model_Story || $this->_backup_Model_Story = new Backup_Model_Story();
		$examineLog = $this->_backup_Model_Story->getExamineLog($storyId);
		if (!$examineLog) {
			return '';
		}

		$this->smarty->assign('examineLog', $examineLog);
		return $this->smarty->fetch('storyExamineLog.tpl');
	}
}